<?php 

if (!defined('CORE_PATH'))
    die('Access Denied');

kan_import('FileManager');

/**
 * Manages the Exporting of file via Zip Format
 */
class ExportManager extends Controller {
	
	public function __construct() {
		
	}
	
	public function zipAndDownloadFolder($folder, $data = NULL ) {
		
		// get a file manager instance
		$fm = new FileManager();
		
		// if the temp directory already exists, then clear it
		$tmpdir = kan_fix_path("../tmp/");
		if( file_exists($tmpdir) ) {
			$fm->deleteDirectory( $tmpdir );
		}
		
		// recreate the directory
		@mkdir($tmpdir);
		
		if( $data != NULL ) {
			
			// encode the supplied content in JSON format
			$content = json_encode($data);
			
			// save the JSON data as a file within the folder to be packaged
			$descript = kan_fix_path($folder . "/data.json");
			file_put_contents( $descript ,$content);
		}
		
		$zipPath = kan_fix_path("../tmp/" . basename($folder) . ".zip" );
		$this->createArchive( $folder, $zipPath );
		$this->downloadFile( $zipPath, NULL, true );
	}
	
	
	private function createArchive($source, $destination) {
		
		if (extension_loaded('zip') === true) {
			
			if (file_exists($source) === true) {
				$zip = new ZipArchive();

				if ($zip->open($destination, ZIPARCHIVE::CREATE) === true) {
					$source = realpath($source);
					$source_fix = str_replace("\\","/",$source); // fix path for Windows Systems

					if (is_dir($source) === true) {
						$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

						foreach ($files as $file) {
							$file = realpath($file);
							$file_fix = str_replace("\\", "/", $file); // fix path for Windows Systems

							if (is_dir($file) === true) {
								$zip->addEmptyDir(str_replace(dirname($source_fix) . '/', '', $file_fix . '/'));
							}

							else if (is_file($file) === true) {
								$zip->addFromString(str_replace(dirname($source_fix) . '/', '', $file_fix), file_get_contents($file));
							}
						}
					}

					else if (is_file($source) === true) {
						$zip->addFromString(basename($source), file_get_contents($source));
					}
				}

				return $zip->close();
			}
		}
	
		return false;
	}
	
	public function downloadFile($path, $fileName = NULL, $deleteAfter = false) {
		
		// check that file exists and is readable
		if (file_exists($path) && is_readable($path)) {
		
		// get the file size and send the http headers
		  $size = filesize($path);
		  $ext = "." . pathinfo($path, PATHINFO_EXTENSION);
		  if( $fileName != NULL && stristr($fileName,$ext) != $ext ) {
			 $fileName = $fileName . $ext;
		  }

		  header('Content-Type: application/octet-stream');
		  header('Content-Length: '.$size);
		  header('Content-Disposition: attachment; filename='. ($fileName != NULL ? $fileName : basename($path)) );
		  header('Content-Transfer-Encoding: binary');
		
		  // open the file in binary read-only mode
		  // display the error messages if the file can't be opened
		  $file = @fopen($path, 'rb');
		
		  if ($file) {
			 // stream the file and exit the script when complete
			 //fpassthru($file);
			 /* fpassthru is apparantly a memory-hog. Use this instead */
			 $bytesSent = -1;
			 
			 while(!feof($file)) {
				$buf = fread($file, 4096);
				echo $buf;
				$bytesSent+=strlen($buf);    /* We know how many bytes were sent to the user */
			 }
			 
			 @fclose($file);
			 
			 // if set to delete the file after download, then delete it if possible
			 if( $bytesSent == filesize($file) ) {
				 if( $deleteAfter ) {
			    	@unlink($path);	 
				 }
			 }
		
		  } else {
			 echo "Could Not Open File For Reading";
		  }
		
		} else {
		  echo "File Does Not Exist: " . $filename;
		  //echo $err;
		}	
	}
}
?>